package com.stylefeng.guns.rest.modular.film;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.rpc.RpcContext;
import com.stylefeng.guns.api.film.FilmAsyncServiceApi;
import com.stylefeng.guns.api.film.FilmServiceApi;
import com.stylefeng.guns.api.film.vo.*;
import com.stylefeng.guns.core.response.ServerResponse;
import com.stylefeng.guns.rest.modular.film.vo.FilmConditionVo;
import com.stylefeng.guns.rest.modular.film.vo.FilmIndexVo;
import com.stylefeng.guns.rest.modular.film.vo.FilmRequestVo;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @Author: jiaru
 * @Description: 电影相关网关
 * @Date: Created on 2019/3/23
 * @Modify:
 */
@RestController
@RequestMapping("/film/")
public class FilmController {

    @Reference
    private FilmServiceApi filmServiceApi;

    @Reference(interfaceClass = FilmAsyncServiceApi.class, async = true, check = false)
    private FilmAsyncServiceApi filmAsyncServiceApi;

    /**
     * API 网关：
     *      1. 功能聚合，API 聚合；
     *          好处：
     *              1. 六个接口，一次请求，同一时刻节省 5 次 HTTP请求
     *              2. 同一接口对外暴露，降低了前后端分离开发的难度和复杂度；
     *          坏处：
     *              1. 一次获取数据过多，容易出现问题
     *      2.
     */

    /**
     * 获取首页信息
     *
     * @return
     */
    @RequestMapping("index")
    public ServerResponse index() {
        FilmIndexVo filmIndexVo = new FilmIndexVo();

        // 获取banner信息
        filmIndexVo.setBanners(filmServiceApi.getBanners());
        // 获取正在热映的电影
        filmIndexVo.setHotFilms(filmServiceApi.getHotFilms(true, 8, 1, 1, 99, 99, 99));
        // 即将上映的电影
        filmIndexVo.setSoonFilms(filmServiceApi.getSoonFilms(true, 8, 1, 1, 99, 99, 99));
        // 票房排行榜
        filmIndexVo.setBoxRanking(filmServiceApi.getBoxRanking());
        // 获取受欢迎的榜单
        filmIndexVo.setExpectRanking(filmServiceApi.getExpectRanking());
        // 获取前一百票房电影
        filmIndexVo.setTop100(filmServiceApi.getTop());

        return ServerResponse.createBySuccess(filmIndexVo);
    }

    @RequestMapping(value = "getConditionList")
    public ServerResponse getConditionList(@RequestParam(name = "catId", required = false, defaultValue = "99") String catId,
                                           @RequestParam(name = "sourceId", required = false, defaultValue = "99") String sourceId,
                                           @RequestParam(name = "yearId", required = false, defaultValue = "99") String yearId) {
        // 标识位
        boolean flag = false;

        // 类型集合
        List<CatVo> cats = filmServiceApi.getCats();
        List<CatVo> catResult = new ArrayList<>();
        CatVo cat = null;
        for (CatVo catVo : cats) {
            // 判断集合是否存在catId，如果存在，则将对应的实体变成active状态
            // 6
            // 1,2,3,99,4,5 ->
            /*
                优化：【理论上】
                    1、数据层查询按Id进行排序【有序集合 -> 有序数组】
                    2、通过二分法查找
             */
            if (catVo.getCatId().equals("99")) {
                cat = catVo;
                continue;
            }
            if (catVo.getCatId().equals(catId)) {
                flag = true;
                catVo.setActive(true);
            } else {
                catVo.setActive(false);
            }
            catResult.add(catVo);
        }
        // 如果不存在，则默认将全部变为Active状态
        if (!flag) {
            cat.setActive(true);
            catResult.add(cat);
        } else {
            cat.setActive(false);
            catResult.add(cat);
        }

        // 片源集合
        flag = false;
        List<SourceVo> sources = filmServiceApi.getSources();
        List<SourceVo> sourceResult = new ArrayList<>();
        SourceVo sourceVo = null;
        for (SourceVo source : sources) {
            if (source.getSourceId().equals("99")) {
                sourceVo = source;
                continue;
            }
            if (source.getSourceId().equals(catId)) {
                flag = true;
                source.setActive(true);
            } else {
                source.setActive(false);
            }
            sourceResult.add(source);
        }
        // 如果不存在，则默认将全部变为Active状态
        if (!flag) {
            sourceVo.setActive(true);
            sourceResult.add(sourceVo);
        } else {
            sourceVo.setActive(false);
            sourceResult.add(sourceVo);
        }

        // 年代集合
        flag = false;
        List<YearVo> years = filmServiceApi.getYears();
        List<YearVo> yearResult = new ArrayList<>();
        YearVo yearVo = null;
        for (YearVo year : years) {
            if (year.getYearId().equals("99")) {
                yearVo = year;
                continue;
            }
            if (year.getYearId().equals(catId)) {
                flag = true;
                year.setActive(true);
            } else {
                year.setActive(false);
            }
            yearResult.add(year);
        }
        // 如果不存在，则默认将全部变为Active状态
        if (!flag) {
            yearVo.setActive(true);
            yearResult.add(yearVo);
        } else {
            yearVo.setActive(false);
            yearResult.add(yearVo);
        }

        FilmConditionVo filmConditionVo = new FilmConditionVo();

        filmConditionVo.setCatInfo(catResult);
        filmConditionVo.setSourceInfo(sourceResult);
        filmConditionVo.setYearInfo(yearResult);


        return ServerResponse.createBySuccess(filmConditionVo);
    }


    @RequestMapping(value = "getFilms")
    public ServerResponse getFilms(FilmRequestVo filmRequestVo) {
        FilmVo filmVo;
        // 根据showType判断影片查询类型
        switch (filmRequestVo.getShowType()) {
            case 1:
                filmVo = filmServiceApi.getHotFilms(
                        false, filmRequestVo.getPageSize(), filmRequestVo.getNowPage(),
                        filmRequestVo.getSortId(), filmRequestVo.getSourceId(), filmRequestVo.getYearId(),
                        filmRequestVo.getCatId());
                break;
            case 2:
                filmVo = filmServiceApi.getSoonFilms(
                        false, filmRequestVo.getPageSize(), filmRequestVo.getNowPage(),
                        filmRequestVo.getSortId(), filmRequestVo.getSourceId(), filmRequestVo.getYearId(),
                        filmRequestVo.getCatId());
                break;
            case 3:
                filmVo = filmServiceApi.getClassicFilms(
                        filmRequestVo.getPageSize(), filmRequestVo.getNowPage(),
                        filmRequestVo.getSortId(), filmRequestVo.getSourceId(),
                        filmRequestVo.getYearId(), filmRequestVo.getCatId());
                break;
            default:
                filmVo = filmServiceApi.getHotFilms(
                        false, filmRequestVo.getPageSize(), filmRequestVo.getNowPage(),
                        filmRequestVo.getSortId(), filmRequestVo.getSourceId(), filmRequestVo.getYearId(),
                        filmRequestVo.getCatId());
                break;
        }

        return ServerResponse.createBySuccess(filmVo);
    }


    @RequestMapping(value = "films/{searchParam}")
    public ServerResponse films(@PathVariable("searchParam") String searchParam, int searchType) throws ExecutionException, InterruptedException {
        // 根据searchType，判断查询类型
        FilmDetailVo filmDetail = filmServiceApi.getFilmDetail(searchType, searchParam);

        if (filmDetail == null) {
            return ServerResponse.createByError("没有可查询的影片");
        } else if (filmDetail.getFilmId() == null || filmDetail.getFilmId().trim().length() == 0) {
            return ServerResponse.createByError("没有可查询的影片");
        }

        String filmId = filmDetail.getFilmId();
        // 查询影片的详细信息 -> Dubbo的异步调用
        // 获取影片描述信息
//        FilmDescVo filmDescVo = filmAsyncServiceApi.getFilmDesc(filmId);
        filmAsyncServiceApi.getFilmDesc(filmId);
        Future<FilmDescVo> filmDescVoFuture = RpcContext.getContext().getFuture();
        // 获取图片信息
        filmAsyncServiceApi.getImgs(filmId);
        Future<ImgVo> imgVoFuture = RpcContext.getContext().getFuture();
        // 获取导演信息
        filmAsyncServiceApi.getDectInfo(filmId);
        Future<ActorVo> actorVoFuture = RpcContext.getContext().getFuture();
        // 获取演员信息
        filmAsyncServiceApi.getActors(filmId);
        Future<List<ActorVo>> actorsVoFutrue = RpcContext.getContext().getFuture();

        // 组织info对象
        InfoRequstVo infoRequstVo = new InfoRequstVo();

        // 组织Actor属性
        ActorRequestVo actorRequestVo = new ActorRequestVo();
        actorRequestVo.setActors(actorsVoFutrue.get());
        actorRequestVo.setDirector(actorVoFuture.get());

        // 组织info对象
        infoRequstVo.setActors(actorRequestVo);
        infoRequstVo.setBiography(filmDescVoFuture.get().getBiography());
        infoRequstVo.setFilmId(filmId);
        infoRequstVo.setImgVo(imgVoFuture.get());

        // 组织成返回值
        filmDetail.setInfo04(infoRequstVo);

        return ServerResponse.createBySuccess(filmDetail);

    }

}
